package com.atguigu.gulimall.ware.listener;

import com.atguigu.common.to.OrderTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Description :库存解锁监听器
 * @Author : mayp
 * @Date: 2021-01-30 22:27
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 这是对库存过期的处理（解锁）
     * @param to
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到库存解锁消息...");
        try{
            // 只要有异常，说明消息消费失败
            wareSkuService.unlockStock(to);//解锁库存方法
            // 如果上面的方法执行成功，需要回复成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            e.printStackTrace();
            // 只要收到异常，就拒绝，然后把消息直接放到队列中，让重新消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /**
     * 订单已被关闭的处理
     * 接收发出去的所有订单数据
     * 也即订单关了，也需要主动解一个库存
     * @param orderTo
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleOrderCloneRekease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭准备解锁库存");
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
